//
//  BaseDownloadCell.m
//  VPDownloadManager
//
//  Created by vernepung on 16/3/10.
//  Copyright © 2016年 vernepung. All rights reserved.
//

#import "VPDownloadCell.h"
static void * const VPOBSERVERCONTEXTKEY = @"VPOBSERVERCONTEXTKEY";
@interface VPDownloadCell ()
{

}
@end

@implementation VPDownloadCell

- (void)dealloc
{
    [self removeObserver];
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)removeObserver
{
    [_currentModel removeObserver:self forKeyPath:@"downloadState" context:VPOBSERVERCONTEXTKEY];
    [_currentModel removeObserver:self forKeyPath:@"readedBytes" context:VPOBSERVERCONTEXTKEY];
}

- (void)setCurrentModel:(VPDownloadModel *)currentModel
{
    if (_currentModel)
    {
        [self removeObserver];
    }
    if (currentModel)
    {
        [currentModel addObserver:self forKeyPath:@"downloadState" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:VPOBSERVERCONTEXTKEY];
        [currentModel addObserver:self forKeyPath:@"readedBytes" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:VPOBSERVERCONTEXTKEY];
    }
    _currentModel = currentModel;
    [self readedBytesUpdated];
    [self downloadStateChanged];
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    dispatch_async(dispatch_get_main_queue(), ^{
        //    NSLog(@"changed %@",keyPath);
        if ([keyPath isEqualToString:@"downloadState"])
        {
            [self downloadStateChanged];
        }
        else if ([keyPath isEqualToString:@"readedBytes"])
        {
            [self readedBytesUpdated];
        }
    });
}

- (void)downloadStateChanged
{

}

- (void)readedBytesUpdated
{
    
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}
- (NSString *)getSize:(long long)bytes
{
    CGFloat size = bytes / 1024.f / 1024.f;
    return [NSString stringWithFormat:@"%.1f",size];
}

@end
